#include "stdafx.h"
#include "file.h"

void Write7BitEncodedSize(FILE *pFile,size_t v)
{
	do
	{
		unsigned char cur = (unsigned char)(v & 0x7f);
		v >>= 7;
		if(v)
			cur |= 0x80;

		if(fwrite(&cur,1,1,pFile) != 1)
			throw WE_WRITE_FAILED;
	}
	while(v);
}

void WriteString(FILE *pFile,const std::string &s)
{
	Write7BitEncodedSize(pFile,s.length());

	// write the string in utf8 encoding
	for(int i = 0;i < (int)s.length();i++)
	{
		if(s[i] < 0x80)
		{
			if(fwrite(&s[i],1,1,pFile) != 1)
				throw WE_WRITE_FAILED;
		}
		else
		{
			unsigned char b1 = 0xc0;
			b1 |= s[i] >> 6;
			if(fwrite(&b1,1,1,pFile) != 1)
				throw WE_WRITE_FAILED;

			unsigned char b2 = 0x80;
			b2 |= s[i] & 0x3f;
			if(fwrite(&b2,1,1,pFile) != 1)
				throw WE_WRITE_FAILED;
		}
	}
}